<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/8
 * Time: 17:43
 */
namespace app\index\controller;

use app\index\controller\CommonController;
use app\index\model\Doctornurse;
use app\index\model\Sets;
use app\index\model\Admin;
use think\Cookie;
use think\Request;
use app\index\model\Data;
use think\Db;
use think\Session;

class Index extends CommonController{
    public function index(){
        $this->redirect("Index/listdata");

    }
    public function add(){
        return $this->fetch("Index/add");
    }

    //弹出式添加
    public function tcadd(){
        //预约页面添加
        $time=input('time');
        $position=input('position');
        $date=input('date');
        if(!empty($time)){
            $timeType=1;
            $time=explode(':',$time);
        }else{
            $timeType=0;
        }
        $this->assign("time",$time);
        $this->assign("position",$position);
        $this->assign("date",$date);
        $this->assign("timeType",$timeType);


        $setsobj = new Sets();
        $data = $setsobj::all();

        $data_array = [];
        $i = 0;
        foreach ($data as $k => $v){
            $itemValue=explode("|",$v['value']);
            if($v['key']=='device'){
                foreach($itemValue as $kk=>$vv){
                    $itemValue[$kk]=explode('-',$vv)[0];
                }
            }

            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = $itemValue;
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }

        //过滤项目
        foreach($data_array[1]['value'] as $key=>$value){
            $itemArr=explode('-',$value);
            $data_array[1]['value'][$key]=$itemArr[0];
        }

        $this->assign("data",$data_array);

        return $this->fetch("Index/tcadd");
    }

    //添加数据
    public function adddata(Request $request){
        $user=explode('-',cookie('auth'))[0];
        if($request->param("name")){
            $result = $request->param();
            $data = new Data();
            $data->riqi = strtotime(str_replace(' ','',$result['date']));
            $data->hongmai = $result['hongmai'];
            $data->shijian = $result['time'];
            $data->shebei = isset($result['device'])?json_encode($result['device'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->name = $result['name'];
            $data->yaoyue = $result['yaoyue'];
            //$data->phone = $result['phone'];
            $data->from = $result['channel'];
            $data->buwei = json_encode($result['position'],JSON_UNESCAPED_UNICODE);
            $data->spendtime = $result['lengthtime'];
            $data->doctor = isset($result['doctor'])?json_encode($result['doctor'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->nurse = isset($result['nurse'])?json_encode($result['nurse'],JSON_UNESCAPED_UNICODE):"{'空'}";
            //$data->zhiliaoshi = isset($result['zhiliaoshi'])?json_encode($result['zhiliaoshi'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->meirongshi = isset($result['meirongshi'])?json_encode($result['meirongshi'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->wenxiushi = isset($result['wenxiushi'])?json_encode($result['wenxiushi'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->tuomaoshi = isset($result['tuomaoshi'])?json_encode($result['tuomaoshi'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->content = $result['message'];
            $data->hushi = isset($result['hushi'])?json_encode($result['hushi'],JSON_UNESCAPED_UNICODE):"{'空'}";
            $data->auser=$user;
            $insert_result = $data->save();

           echo 1;
        }else{
            echo json_encode(array("msg"=>"data error"));
        }
    }
    //获取项目预约时长
    public  function  getPosition(Request $request){

        $position=input('position');

        $setsobj = new Sets();
        $data = $setsobj::all();

        $lenTime=[];
        $arrValue=explode('|',$data[1]['value']);
        //dd($arrValue);
        foreach($arrValue as $key=>$value){
            if(empty($position))break;
            if(substr_count($value,$position)){
                $itemArr=explode('-',$value);
                if(!empty($itemArr[1])){
                    $itemArr=explode(',',$itemArr[1]);
                    $lenTime['data']=$itemArr;
                    break;
                }
            }
        }
        if(empty($lenTime['data'])){
            $lenTime['data']=[1,1.5,2,2.5,3,3.5,4];
        }

        return $lenTime;
    }

    //数据列表
    public function listdata(Request $request){
        $this->redirect('search_gk');//跳转


		$username = explode('-',Cookie::get('auth'))[0];
        $roleid = Admin::where("uname",$username)->column("urole");

        $this->assign("roleid",$roleid[0]);

        if($request->param("date")){
            $riqi = strtotime(str_replace(' ','',$request->param("date")));
        }else{
            $riqi = strtotime(date("Y-n-j"));
        }

        $data = new Data();

        //$datas = $data->where("riqi",$riqi)->select();
        $datas=Db::query("select * from data where riqi='{$riqi}'");
        

        //排序逻辑
        if(!empty($datas)){
            foreach($datas as $key=>$value){
                $ymdData=date('Y-m-d',$value['riqi']);
                $term=explode(':',$value['shijian']);
                $datas[$key]['shijian']=$ymdData.' '.$value['shijian'];
                //dump($term);exit;
                $multiArr[]=$value['riqi']+$term[0]*3600+$term[1]*60;

                $spendtime=str_replace(array('小时','分钟'),'',$value['spendtime']);
                if($spendtime<10){
                    $min=$spendtime*60;
                }else{
                    $min=$spendtime;
                }
                $datas[$key]['shijianX']=$datas[$key]['shijian'].'-'.date('H:i',strtotime($datas[$key]['shijian'])+$min*60);
                $datas[$key]['freeType']=0;
            }
            array_multisort($multiArr,SORT_ASC,$datas);
        }


        session('datas',$datas);

        $this->assign("data",$datas);


        //查询仪器情况
        $setsobj = new Sets();
        $sets_tmp = $setsobj::all();
        $data_array = [];
        $i = 0;
        foreach ($sets_tmp as $k => $v){
            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = explode("|",$v['value']);
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }
        $this->assign("device_status",$data_array);

        //排班数据
        $pbtmparr = $request->param();
        if(array_key_exists("date",$pbtmparr)){
            $pbdate = $request->param("date");
        }else{
            $pbdate  = date("Y-n-j");
        }

        //dd($pbdate);
        $paiban_data = Doctornurse::get(['d_date' => str_replace(' ','',$pbdate)]);

        $paiban_arr = [];
        $paiban_arr['d_doctor'] = array_values((array)json_decode($paiban_data['d_doctor'],JSON_UNESCAPED_UNICODE));
        $paiban_arr['d_nurse'] = array_values((array)json_decode($paiban_data['d_nurse'],JSON_UNESCAPED_UNICODE));

        if(sizeof($paiban_arr['d_doctor'])>0){$this->assign("paiban_data",$paiban_arr);}


        if(isMobile()){
            return $this->fetch("Index/listmobile");
        }else{

            return $this->fetch("Index/list");
        }

    }

    //数据列表搜索
    public function search_gk(Request $request){
		$username = explode('-',Cookie::get('auth'))[0];
        $roleid = Admin::where("uname",$username)->column("urole");

        $this->assign("roleid",$roleid[0]);
		
        $data = $request->param();

        $where="";
        if(!empty($data["logmin"])||!empty($data["logmax"])||!empty($data["gk_name"])){
            $where = "where ";
        }
        //如果三个条件都是空
        if(empty($data["logmin"])&&empty($data["logmax"])&&empty($data["gk_name"])){
            $where = "where `riqi`=".strtotime(date("Y-m-d"));
        }

        if(!empty($data["logmin"])){
            //非空
            $logmin = strtotime($data['logmin']);
            $where .= "`riqi`>=$logmin ";
        }

        if(!empty($data["logmax"])){
            $logmax = strtotime($data['logmax']);
            $where = $where."and `riqi`<=$logmax ";
        }

        if(!empty($data["gk_name"])){
            $gk_name = $data['gk_name'];
            if(trim($where)=="where"){
                $where1 = $where."shebei like '%{$gk_name}%'";
                $where2 = $where."`name` like '%{$gk_name}%'";
                $where3 = $where."doctor like '%{$gk_name}%' or meirongshi like '%{$gk_name}%'";
            }else{
                $where1 = $where." and   shebei like '%{$gk_name}%' ";
                $where2 = $where." and  `name` like '%{$gk_name}%'";
                $where3 = $where." and  ( doctor like '%{$gk_name}%' or meirongshi like '%{$gk_name}%')";
            }
            $whereArr=array($where1,$where2,$where3);
        }else{
            $whereArr=array();
        }

        //dump($whereArr);exit;

        if(empty($whereArr)){
            $result = Db::query("select * from data $where");
        }else{
            foreach($whereArr as $key=>$value){
                $result = Db::query("select * from data $value");
                if(!empty($result)){
                    break;
                }
            }
        }



        $this->assign("search_data",$data);


        //排序逻辑
        if(!empty($result)){
            foreach($result as $key=>$value){

                $spendtime=str_replace(array('小时','分钟'),'',$value['spendtime']);
                if($spendtime<10){
                    $min=$spendtime*60;
                }else{
                    $min=$spendtime;
                }

                $ymdData=date('Y-m-d',$value['riqi']);
                $result[$key]['shijian']=$ymdData.' '.$value['shijian'];
                $result[$key]['numberSj']=strtotime($result[$key]['shijian']);
                $result[$key]['shijianX']=$result[$key]['shijian'].'-'.date('H:i',strtotime($result[$key]['shijian'])+$min*60);
                $result[$key]['freeType']=0;
                $result[$key]['auserType']=0;
                $multiArr[]=$value['riqi'];
            }
            array_multisort($multiArr,SORT_DESC,$result);
        }

        //获取空闲时间段
        if(!empty($data["gk_name"])&&!empty($data["logmin"])&&$data["logmax"]==$data["logmin"]){

            $freeData=$this->freeTime($result,$data["gk_name"],$data["logmin"]);
            $freeData['nArrF']='';


            //
            if(!empty($freeData['shijian'])){
                $shijianArr=explode('<br>',$freeData['shijian']);
                $itemFreeArr=$freeData;
                foreach($shijianArr as $key=>$value){
                    if($key!=0){
                        $itemArr=explode('-',$value);
                        $itemFreeArr['shijian']=$shijianArr[0].' '.$value;
                        $itemFreeArr['shijianX']=$itemFreeArr['shijian'];
                        $itemFreeArr['numberSj']=strtotime($shijianArr[0].' '.$itemArr[0]);
                        $itemFreeArr['freeType']=1;//空闲标识
                        if(!empty($freeData))array_push($result,$itemFreeArr);
                    }
                }
            }

//            dd($shijianArr);
//            dd($result);
//            exit;
        }


        //排序逻辑
        $volArr=[];
        $user=explode('-',cookie('auth'))[0];
        //dd($result);exit;
        foreach($result as $key=>$value){
            $result[$key]['shijian']=substr($value['shijianX'],5,50);
            $volArr[$key]=$value['numberSj'];
            if(!empty($value['auser'])){
                if($value['auser']==$user||$user=='pcyy'){//有修改权限
                    $result[$key]['auserType']=1;
                }else{
                    $result[$key]['auserType']=0;
                }
            }
        }
        array_multisort($volArr,SORT_ASC,$result);
        str_replace('<br>','',$result);

//        dd($result);
//        exit;

        session('datas',$result);
        $this->assign("data",$result);


        if(isMobile()){
            return $this->fetch("Index/listmobileFree");
        }else{

            return $this->fetch("Index/list");
        }
    }
    public  function freeTime($resultData,$name,$logmin=null){//空闲时间

        if(!empty($resultData[0])){
            $freeData=$resultData[0];
            foreach($freeData as $key=>$value){$freeData[$key]='';}
            $freeData['riqi']=$resultData[0]['riqi'];
        }else{
            //$freeData['riqi']=strtotime(date("Y-n-j"));
            $freeData['riqi']=strtotime($logmin);
            $itemArr=array('d_id','hongmai','from','content','zhiliaoshi','shijian','yaoyue','buwei','spendtime','shebei','doctor','meirongshi','tuomaoshi','wenxiushi','done');
            foreach ($itemArr as $key => $value) {
                $freeData[$value]='';
            }
        }
        $freeData['name']='空闲';
        //dd($freeData);exit;


        $logmin = $freeData['riqi'];
        $date=date('Y-m-d',$logmin);
        $ymdArr=explode('-',$date);

        //医生护士信息
        $setsobj = new Sets();
        $data = $setsobj::all();
        $data_array = [];
        $i = 0;
        foreach ($data as $k => $v){
            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = explode("|",$v['value']);
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }
        $nameArr=array();
        $nameArr=array_merge($nameArr,$data_array[4]['value'],$data_array[7]['value']);
        //排班信息
        $Set=controller('Set');
        $data=$Set->getExcel();
        $dateArr=$data[1];
        foreach($dateArr as $key=>$value){
            $dateArr[$value]=$key;
        }
        $nameData=array();

        foreach($nameArr as $key=>$value){
            foreach($data as $k=>$v){
                if(empty($value)||empty($v['B'])){
                    break;
                }
                if(substr_count($value,$v['B'])){
                    $nameData[$key]['name']=$value;
                    $nameData[$key]['work']=$v[$dateArr[intval($ymdArr[2])]];
                    break;
                }
            }
        }

        foreach($nameData as $key=>$value){
            if(substr_count($value['name'],$name)){
                $work=$value['work'];break;
            }
        }



        //空闲范围
        if(empty($work)){//非医疗人员
            $nodeArr=freeTimeShebei($resultData,$name);
            //if(empty($nodeArr))return ;
            $qd=9*2-1;$zd=20*2-1;   //8:30-20:00
        }else{
            //$freeData['doctor']=$resultData[0]['doctor'];

            $nodeArr=[];
            //dd($resultData);
            foreach($resultData as $key=>$value){
                if($logmin!=$value['riqi']){
                    break;
                }
                $hourStr=date('H:i',strtotime($value['shijian']));
                $hourArr=explode(':',$hourStr);
                $hour=$hourArr[0];
                $spendtime=str_replace(array('小时','分钟'),'',$value['spendtime']);

                if($spendtime<10){
                    $min=$spendtime*60;
                }else{
                    $min=$spendtime;
                }

                $qd=$hourArr[0]*2+intval($hourArr[1]/30);
                $zd=$qd+intval($min/30);
                for($i=$qd;$i<$zd;$i++){
                    array_push($nodeArr,$i);
                }

            }
            sort($nodeArr);
            //dd($nodeArr);

            //半小时为节点
            if($work=='早'){
//                $qd=9*2;$zd=18*2-1;
                $qd=9*2-1;$zd=18*2-2;   //8:30-17:30
            }else if($work=='中'){
                $qd=10*2;$zd=19*2-1;
            } else if($work=='晚'){
                $qd=11*2;$zd=20*2-1;
            }
            else{
                return '';
            }

        }



        $nodeArrFree=[];
        for($i=$qd;$i<=$zd;$i++){
            array_push($nodeArrFree,$i);
        }
        //dd($nodeArrFree);
//        dd($nodeArr);
//        exit;
        if($nodeArr==0)return;
        $nArrF=array_values(array_diff($nodeArrFree,$nodeArr));//空闲节点


        //dd($nArrF);

        $itemArrN=[];
        $itemArrD=[];
        foreach($nArrF as $key=>$value){
            if($key<count($nArrF)-1){
                array_push($itemArrN,$value);
                if($nArrF[$key+1]>$value+1){
                    array_push($itemArrD,$itemArrN);
                    $itemArrN=[];

                }
            }else if($key==count($nArrF)-1){
                array_push($itemArrN,$value);
                array_push($itemArrD,$itemArrN);
                $itemArrN=[];
            }
        }



        $freeSecondArr=[];
        array_push($freeSecondArr,$date);



        foreach($itemArrD as $key=>$value){
            $itemCount=count($itemArrD);

            $second1=date('H:i',$value[0]*30*60+$logmin);

            $count=count($value);
            $second2=date('H:i',($value[$count-1]+1)*30*60+$logmin);

            array_push($freeSecondArr,"{$second1}-{$second2}");
        }

//        dd($freeSecondArr);
        //exit;

        $freeData['nArrF']=$nArrF;
        $freeData['shijian']=implode("<br>",$freeSecondArr);

        //dd($nodeArr);dd($freeData);exit;

        return $freeData;
    }

    //数据列表排序
    public function dataorder(Request $request){

        $data = $request->param();



        //排序日期存储在cookie中，防止在同一天中多次点击多条件排序
        if(!empty(explode("=",$_SERVER['HTTP_REFERER'])[1])){
            Cookie::set("order_day",explode("=",$_SERVER['HTTP_REFERER'])[1],3600);
            $order_c_data = explode("=",$_SERVER['HTTP_REFERER'])[1];
        }else{
            $order_c_data = Cookie::get("order_day");
        }


        $data["order_c_data"] = $order_c_data;
        //order_date
        $order_date = $data['order_date'];
        $order_d = $order_date?strtotime($order_date):strtotime(date("Y-m-d"));

        $sql = "SELECT * FROM `data` where riqi=$order_d ORDER BY ";
        if(array_key_exists("order_id",$data)){
            //存在id排序
            if(array_key_exists("order_id_way",$data)){
                $sql .= "`d_id` asc";
            }else{
                $sql .= "`d_id` desc";
            }
        }

        if(array_key_exists("order_name",$data)){
            //存在姓名排序
            if(array_key_exists("order_name_way",$data)){
                if(array_key_exists("order_id",$data)){
                    $sql .= ",`name` asc";
                }else{
                    $sql .= "`name` asc";
                }

            }else{
                if(array_key_exists("order_id",$data)){
                    $sql .= ",`name` desc";
                }else{
                    $sql .= "`name` desc";
                }

            }
        }

        if(array_key_exists("order_item",$data)){
            //存在项目排序
            if(array_key_exists("order_item_way",$data)){
                if(array_key_exists("order_id",$data)||array_key_exists("order_name",$data)){
                    $sql .= ",`buwei` asc";
                }else{
                    $sql .= "`buwei` asc";
                }

            }else{
                if(array_key_exists("order_id",$data)||array_key_exists("order_name",$data)){
                    $sql .= ",`buwei` desc";
                }else{
                    $sql .= "`buwei` desc";
                }
            }
        }



        $result = Db::query($sql);
        $this->assign("data",$result);
        $this->assign("check_data",$data);

        //查询仪器情况
        $setsobj = new Sets();
        $sets_tmp = $setsobj::all();
        $data_array = [];
        $i = 0;
        foreach ($sets_tmp as $k => $v){
            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = explode("|",$v['value']);
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }
        $this->assign("device_status",$data_array);

        //查询专家排班表
        $paiban_data = Doctornurse::get(['d_date' => str_replace(' ','',$request->param("order_date"))]);

        $paiban_arr = [];
        $paiban_arr['d_doctor'] = array_values((array)json_decode($paiban_data['d_doctor'],JSON_UNESCAPED_UNICODE));
        $paiban_arr['d_nurse'] = array_values((array)json_decode($paiban_data['d_nurse'],JSON_UNESCAPED_UNICODE));

        if(sizeof($paiban_arr['d_doctor'])>0){$this->assign("paiban_data",$paiban_arr);}

       // $this->assign("paiban_data",$paiban_arr);
        return $this->fetch("Index/order");

    }



    //设置已经治疗
    public function setDone(Request $request){
        if($request->param("id")){
            $data = Data::get($request->param('id'));
            $data->done=1;      //将该记录设置成已治疗
            if($data->save()){
                echo "success";
            }else{
                echo "error";
            }
        }else{
            echo json_encode(array("msg"=>"id is must"));
        }
    }

    //修改状态，需要接收参数id
    public function modify(Request $request){
        if($request->param('id')){
            if(input('stype')){
                $stype=input('stype');
            }else{
                $stype=0;
            }

            $data = Data::get($request->param('id'));

            //判断id是否能查出数据，如果不能终止执行
            if(!$data){
                echo "no data";
                exit(0);
            }


            $this->assign('recode_data',$data);
            //dd($data);
            //查询仪器情况
            $setsobj = new Sets();
            $sets_tmp = $setsobj::all();
            $data_array = [];
            $i = 0;


            foreach ($sets_tmp as $k => $v){
                $data_array[$i]['id'] = $v['id'];
                $data_array[$i]['key'] = $v['key'];
                $data_array[$i]['value'] = explode("|",$v['value']);
                $data_array[$i]['status'] = $v['status'];
                $i++;
            }

            //过滤
            foreach($data_array[0]['value'] as $key=>$value){
                $item=explode('-',$value);
                $data_array[0]['value'][$key]=$item[0];
            }
            foreach($data_array[1]['value'] as $key=>$value){
                $item=explode('-',$value);
                $data_array[1]['value'][$key]=$item[0];
            }


            $data_array['stype']=$stype;

           $this->assign("data",$data_array);

            //dd($data_array);
            //dd($data_array[0]['value']);
            //exit;
            return $this->fetch("Index/modify");
        }else{
            echo json_encode(array("msg"=>"modify id is must"));
        }
    }

    //接收修改数据
    public function modifydata(Request $request){

        if($request->param("name")){
            $result = $request->param();
            $data = new Data;

            $re = $data->save([
                "riqi"=>strtotime(str_replace(' ','',$result['date'])),
                "hongmai"=>$result['hongmai'],
                "shijian"=>$result['time'],
                "shebei"=>json_encode($result['device'],JSON_UNESCAPED_UNICODE),
                "name"=>$result['name'],
                "yaoyue"=>$result['yaoyue']?$result['yaoyue']:"空",
//                "phone"=>$result['phone'],
                "from"=>$result['channel'],
                "buwei"=>json_encode($result['position'],JSON_UNESCAPED_UNICODE),
                "spendtime"=>$result['lengthtime'],
                "doctor"=>isset($result['doctor'])?json_encode($result['doctor'],JSON_UNESCAPED_UNICODE):"{'空'}",
                "zhiliaoshi"=>isset($result['zhiliaoshi'])?json_encode($result['zhiliaoshi'],JSON_UNESCAPED_UNICODE):"{'空'}",
                "meirongshi"=>isset($result['meirongshi'])?json_encode($result['meirongshi'],JSON_UNESCAPED_UNICODE):"{'空'}",
                "content"=>$result['message']
//                "hushi"=>isset($result['hushi'])?json_encode($result['hushi'],JSON_UNESCAPED_UNICODE):"{'空'}",
            ],["d_id"=>$result['d_id']]);
            return $re;

        }else{
            echo json_encode(array("msg"=>"modify error"));
        }
    }

    //数据分析页面
    public function ansypage(){

        return $this->fetch("Index/ansy");
    }

    //返回生成图表数据
    public function ansyfrom(Request $request){

        $data_range = $request->param("date_range");
        $from_type  = $request->param("from_type");     //渠道、项目
        $map_type   = $request->param("map_type");      //圆饼、折线

        $data_arr = explode(" - ",$data_range);

        //查询的时间范围
        $date_start = strtotime($data_arr[0]);
        $date_end = strtotime($data_arr[1]);

        //查询sets表中的字段
        $sets_result = Sets::where('key','from')->value('value');
        $sets_arr = explode("|",$sets_result);

        //查询项目数组
        $projects_result = Sets::where('key','project')->value('value');
        $projects_arr = explode("|",$projects_result);

        //选择分析的种类
        $arr_from_type = [
            'canal' =>  $sets_arr,
            'item' =>   $projects_arr
        ];

        //是用什么图来表示,
        $map_type = ["pie","category"];

        switch ($from_type){
            case "渠道":
                $canal = json_encode($arr_from_type['canal'],JSON_UNESCAPED_UNICODE);

                $result = Db::query("SELECT COUNT(*) AS `sum`,`from`,riqi FROM ( SELECT * FROM `data` WHERE riqi>=$date_start AND riqi<=$date_end ) AS a GROUP BY `from`;");

                //dd($result);


                //生成json数据
                $groupcanalarr = [];
                foreach ($result as $k => $v){
                    $groupcanalarr[$k]['value'] = $v['sum'];
                    $groupcanalarr[$k]['name'] = $v['from'];
                }

                $json_group = json_encode($groupcanalarr,JSON_UNESCAPED_UNICODE);

                $json = <<<EOF
{
        title : {
            text: '渠道占比',
            subtext: '',
            x:'center'
        },
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            data: $canal
        },
        series : [
            {
                name: '来源',
                type: 'pie',
                radius : '55%',
                center: ['50%', '60%'],
                data:$json_group,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    }
EOF;
                //圆饼图
                //echo $json;

                //折线图
                $zhexiandata = Db::query("SELECT COUNT(*) AS `sum`,`from`,FROM_UNIXTIME(riqi,'%m-%d') AS riqi FROM ( SELECT * FROM `data` WHERE riqi>=$date_start AND riqi<=$date_end ) AS a GROUP BY `riqi`;");

                $date_arr = [];
                $num_arr = [];
                foreach ($zhexiandata as $a => $b){
                    array_push($date_arr,$b['riqi']);
                    array_push($num_arr,$b['sum']);
                }
                $date_arr = json_encode($date_arr,JSON_UNESCAPED_UNICODE);
                $num_arr = json_encode($num_arr,JSON_UNESCAPED_UNICODE);


                $zx_json = <<<EOF
 {
    color: ['#3398DB'],
    tooltip : {
        trigger: 'axis',
        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis : [
        {
            type : 'category',
            data : $date_arr,
            axisTick: {
                alignWithLabel: true
            }
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'治疗人数',
            type:'bar',
            barWidth: '60%',
            data:$num_arr
        }
    ]
}
EOF;

                //合并数据
                $total_arr = json_encode(["pie"=>$json,"zx"=>$zx_json],JSON_UNESCAPED_UNICODE);
                echo $total_arr;
                break;
            case "项目":
                break;
        }
    }
	
	//删除单个
    public function deleteRecode(Request $request){
        $ids = $request->param("ids");

        $arrData=Db::query("select * from data where d_id='{$ids}'");

        $json=json_encode($arrData[0],JSON_UNESCAPED_UNICODE);
        $json=str_replace(array("{'空'}","\\\""),'',$json);
        //dd($json);
        $riqi=time();
        $user=explode('-',cookie('auth'))[0];
        Db::query("insert into deletedata (uname,riqi,text)values('{$user}','{$riqi}','{$json}')");

        $result = Data::destroy($ids);
        echo $result;
    }


    //查询
    /*
    public function search_gk(Request $request){
        $data = $request->param();
        if(array_key_exists('logmin',$data)){

            //查询有日期限制
            $logmin = strtotime($data['logmin']);
            $logmax = strtotime($data['logmax']);

            $gk_name = $data["gk_name"];
            $data = new Data();
            if($gk_name){
                $search_data = $data->where("riqi",'>=',$logmin)->where("riqi",'<=',$logmax)->where("name","like","%{$gk_name}%")->select();
            }else{
                $search_data = $data->where("riqi",'>=',$logmin)->where("riqi",'<=',$logmax)->select();
            }


            $return_data = [];
            foreach($search_data as $k => $v){
                array_push($return_data,$v);
            }
            echo json_encode($return_data,JSON_UNESCAPED_UNICODE);
        }else{
            //查询没有日期限制
            $gk_name = $data["gk_name"];
            $data = new Data();
            $search_data = $data->where("name","like","%{$gk_name}%")->select();
            echo json_encode($search_data,JSON_UNESCAPED_UNICODE);
        }
    }
*/
    //获取排班信息
    public  function  getPaiban(Request $request){

        //d_id获取
        $d_id=input('did');
        if(empty($d_id)){
            $d_id=0;
        }

        $result=$request->param();
        if(!empty($result['position'])){
            $positionArr=$result['position'];
        }


        //获取小时分钟
        $time=$request->param("time");
        $timeArr=explode(':',$time);
        if(!empty($time)){
            $minNum=$timeArr[0]*60+$timeArr[1];
        }else{$minNum=0;}


        $date=$request->param("date");
        if(empty($date)) $date=date('Y-m-d',time());
        $ymdArr=explode('-',$date);

        $today=date('Y-m-d',time());
        $todayArr=explode('-',$today);


//        if($todayArr[0]!=intval($ymdArr[0])||$todayArr[1]!=intval($ymdArr[1])){//不在同一个月份
//            $type=2;
//        }else{
            $type=1;
//        }


        //医生护士信息
        $setsobj = new Sets();
        $data = $setsobj::all();
        $data_array = [];
        $i = 0;
        foreach ($data as $k => $v){
            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = explode("|",$v['value']);
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }


        $nameArr=array();
        $nameArr=array_merge($nameArr,$data_array[4]['value'],$data_array[7]['value']);

        $nameArr['code']=$type;
        if($type==2)return $nameArr;

        //排班信息
        $Set=controller('Set');
        $data=$Set->getExcel();
        $dateArr=$data[1];
        foreach($dateArr as $key=>$value){
            $dateArr[$value]=$key;
        }




        $nameData=array();
        foreach($nameArr as $key=>$value){
            foreach($data as $k=>$v){
                if(empty($value)||empty($v['B'])){
                    break;
                }
                if(substr_count($value,$v['B'])){
                    $nameData[$key]['name']=$value;
                    $nameData[$key]['work']=$v[$dateArr[intval($ymdArr[2])]];
                    break;
                }
            }
        }


        $nameData['code']=$type;

        //预约情况
        $riqi = strtotime(str_replace(' ','',$date));
        $datas=Db::query("select * from data where riqi='{$riqi}' and d_id!='{$d_id}' order by d_id desc");


        //return $datas;
        //dd($datas);

        foreach($nameData as $key=>$value){
            $itemArr=[];
            foreach($datas as $k=>$v){
                $itemStr=$v['doctor'].$v['meirongshi'].$v['hushi'];
                if(!empty($value['name'])){
                    $conuntNum=substr_count($itemStr,$value['name']);
                }else{
                    $conuntNum=0;
                }
                if($conuntNum){
                    array_push($itemArr,$v);

                    $shijian=$v['shijian'];
                    $sjArr=explode(':',$shijian);
                    $spendtime=$v['spendtime'];
                    $spendtime=str_replace(array('小时','分钟'),'',$spendtime);


                    if($spendtime<10){
                        $min=$spendtime*60;
                    }else{
                        $min=$spendtime;
                    }

                    $min+=$sjArr[1];
                    $hour=$sjArr[0]+floor($min/60);
                    $min=$min%60;

                    if($minNum<$hour*60+$min){
                        $nameData[$key]['disabled']=1;
                    }else{
                        $nameData[$key]['disabled']=0;
                    }



//                    dump($nameData);
//                    exit;
                }
            }

            if(!empty($itemArr)){//空闲时间判断
                $freeTimedata=$this->freeTime($itemArr,$value['name']);
                $freeTimeArr=explode('<br>',$freeTimedata['shijian']);
                $freeTimeArr[0]='';
                $freeTimeArr=array_filter($freeTimeArr);
                foreach($freeTimeArr as $k=>$v){
                    $item1=explode('-',$v);
                    $item1i=explode(':',$item1[0]);
                    $itemMinX=$item1i[0]*60+$item1i[1];//空闲开始时间
                    $item1i=explode(':',$item1[1]);
                    $itemMinY=$item1i[0]*60+$item1i[1];//空闲结束时间



                    if($minNum>=$itemMinX&&$minNum<$itemMinY){
//                        if('余港主任组'==$value['name']){
//                            dd($minNum."_".$itemMinX."_".$itemMinY);
//                        }
                        $nameData[$key]['disabled']=0;break;
                    }else{
                        $nameData[$key]['disabled']=1;
                    }
                }
            }
        }

        //dd($nameData);

        //过去时间过滤
        $dateX=strtotime(date('Y-m-d',time()));
        $dateY=strtotime(intval($ymdArr[0]).'-'.intval($ymdArr[1]).'-'.intval($ymdArr[2]));
//        $todayHi=date("H:i",time());
//        $Hiarr=explode(':',$todayHi);
//        if($minNum<$Hiarr[0]*60+$Hiarr[1]){
//            foreach($nameData as $key=>$value){
//                if(!empty($value['name'])&&$dateY<=$dateX){
//                        $nameData[$key]['disabled']=2;
//                }
//            }
//        }

        //第二天才可以选过滤
        if($dateY<=$dateX){
            foreach($nameData as $key=>$value){
                if(!empty($value['name'])){
                        $nameData[$key]['disabled']=2;
                }
            }
        }


        //医疗项目人员过滤
        if(!empty($positionArr)){
            $setsAll =Db::query("select * from sets where id=22 or id=23 or id=24 or id=25");

            foreach($nameData as $key=>$value){
                foreach($setsAll as $k=>$v){
                    $itemPs=2;
                    if(!empty($value['name'])){
                        for($i=0;$i<count($positionArr);$i++){
                            if(substr_count($v['value'],$value['name'])&&substr_count($v['value'],$positionArr[$i])){
                                $nameData[$key]['position']=1;
                                $itemPs=1;
                                break;
                            }else{
                                $nameData[$key]['position']=2;
                            }
                        }
                    }
                    if($itemPs==1){
                        break;
                    }

                }
            }

//            foreach($positionArr as $key=>$value){
//            }
        }

        //exit;

        //$nameData['position']=$position;

        return $nameData;
        //echo json_encode($nameData,JSON_UNESCAPED_UNICODE);
    }


    public  function  updateLengthtime(Request $request){//更新判断预约时长

        $d_id=input('did');
        if(empty($d_id))$d_id=0;

        if(!empty($_REQUEST['meirongshi']))$doctor=$_REQUEST['meirongshi'];
        if(!empty($_REQUEST['doctor']))$doctor=$_REQUEST['doctor'];


        //获取预约时长
        $spendtime=str_replace(array('小时','分钟'),'',$request->param("lengthtime"));
        if($spendtime<10){
            $lengthtime=$spendtime*60;
        }else{
            $lengthtime=$spendtime;
        }

        //获取小时分钟
        $time=$request->param("time");
        $timeArr=explode(':',$time);


        $qd=$timeArr[0]*2+intval($timeArr[1]/30);
        $zd=$qd+intval($lengthtime/30)-1;

        $nodeArrFree=[];
        for($i=$qd;$i<=$zd;$i++){
            array_push($nodeArrFree,$i);
        }


        //日期
        $date=$request->param("date");
        if(empty($date)) $date=date('Y-m-d',time());
        $riqi = strtotime(str_replace(' ','',$date));

        $datas=Db::query("select * from data where riqi='{$riqi}' and d_id!='{$d_id}' and (doctor like '%{$doctor}%' or meirongshi like '%{$doctor}%') order by d_id desc");

        if(!empty($datas)){//预约时长空闲时间判断
            $freeTimedata=$this->freeTime($datas,$doctor);
            $nArrF=$freeTimedata['nArrF'];

            $nodeArrFree=array_diff($nodeArrFree,$nArrF);
            if(empty($nodeArrFree)){//在空闲时间范围
                $type=0;
            }else{
                $type=1;
            }

            $returnData=['code'=>$type,'freeTimedata'=>$freeTimedata['shijian']];

            return $returnData;
        }

    }

    public  function getDevice(Request $request){//更新设备
        $d_id=input('did');
        if(empty($d_id))$d_id=0;

        //获取小时分钟
        $spendtime=str_replace(array('小时','分钟'),'',$request->param("lengthtime"));
        if($spendtime<10){
            $lengthtime=$spendtime*60;
        }else{
            $lengthtime=$spendtime;
        }
        $device=$request->param("device");


        $time=$request->param("time");
        $timeArr=explode(':',$time);
        if(!empty($time)){
            $minNum=$timeArr[0]*60+$timeArr[1];
        }


        //日期
        $date=$request->param("date");
        if(empty($date)) $date=date('Y-m-d',time());
        $riqi = strtotime(str_replace(' ','',$date));

        $datas=Db::query("select riqi,shebei,spendtime,shijian from data where riqi='{$riqi}' and d_id!='{$d_id}' order by d_id desc");



        $deviceStr='';
        foreach($datas as $key=>$value){
            $sjItem=explode(':',$value['shijian']);
            $stItem=str_replace(array('小时','分钟'),'',$value['spendtime']);
            if($stItem>=10){
                $stItem/=60;
            }

            $minTimeX=$sjItem[0]*60+$sjItem[1];//设备开始时间
            $minTime=$stItem*60+$sjItem[0]*60+$sjItem[1];//设备结束时间
            if($minNum>=$minTime||$minNum+$lengthtime<=$minTimeX){
                $datas[$key]='';
            }else if(!empty($device)){
                if(substr_count($value['shebei'],$device)){
                    $deviceStr.=$value['shijian'].'-'.date('H:i',$minTime*60+$riqi).'<br>';
                }

            }
//            dd($minTime);
//            dd($minNum);
//            exit;

        }
        $datas=array_filter($datas);



        //dd($datas);

        $setsArr=Db::query("select value from sets where id=3");
        $setsArr=explode('|',$setsArr[0]['value']);
        foreach($setsArr as $key=>$value){
            $item=explode('-',$value);

            $setsArrD[$key]['name']=$item[0];
            if(empty($item[1])){
                $setsArrD[$key]['number']=0;
            }else{
                foreach($datas as $k=>$v){
                    $itemNum=substr_count($v['shebei'],$item[0]);
                    if($itemNum){
                        $item[1]-=1;
                    }
                }
                $setsArrD[$key]['number']=intval($item[1]);
            }

            $setsArrD[$key]['deviceStr']='';
            if(!empty($device)){
                if(substr_count($device,$item[0])){
                    $setsArrD[$key]['deviceStr']=$deviceStr;
                }
            }

        }

        //dd($setsArrD);exit;

        $setsArrD['code']=1;
        return $setsArrD;
    }
    //导出文件
    public  function createFile(){
        $this->clearFile("Api/data");

        $fileName='file.xls';
        $arrData=array(
            'fileName'=>$fileName,
            'datas'=> session('datas')
        );

        $json=json_encode($arrData,JSON_UNESCAPED_UNICODE);
        $strData=array('data'=>$json);

        $part=$_SERVER['SERVER_NAME']."/Api/data/{$fileName}";
        $data=array('code'=>1,'part'=>$part);

        $url=$_SERVER['SERVER_NAME'].'/Api/createFile.php';
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url); //设置请求地址
        curl_setopt($ch,CURLOPT_POST,true); //post请求
        curl_setopt($ch,CURLOPT_POSTFIELDS,$strData);// post请求的数据
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);//不需要证书验证
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);//不直接输出到页面
        $json = curl_exec($ch);
        curl_close($ch);

        return $data;
    }
    //清理过期文件
    public  function clearFile($path)
    {
        $pathFile = opendir($path);
        while (($item = readdir($pathFile)) != false) {
            if ($item == '.' || $item == '..') {
                continue;
            } else {
                $file = $path.'/'.$item;
                $times = time()-filemtime($file);
                if($times>24*3600){
                    unlink($file);
                }
            }
        }
    }
    //查询删除的文件
    public  function selectDeleteData(){
        $arr=Db::query("select id from deletedata where stype=0");
        $count=count($arr);
        echo $count;
    }
    //查询删除记录
    public  function DeleteData(Request $request){

        $data = $request->param();

        if(!empty($data["logmin"])&&!empty($data["logmax"])){
            $this->assign("search_data",$data);

            $logmin=strtotime($data["logmin"]);
            $logmax=strtotime($data["logmax"].' 23:59');
            $arr=Db::query("select * from deletedata where riqi>='{$logmin}' and riqi<'{$logmax}' ORDER  by id DESC ");
        }else{
            $arr=Db::query("select * from deletedata where stype=0 ORDER  by id DESC");
            Db::query("update deletedata set stype=1 where stype=0");
        }

        $arrData=array();
        if(!empty($arr)){
            foreach($arr as $key=>$value){
                $data=json_decode($value['text'],true);
                $riqi=date('Y-m-d H:i',$value['riqi']);
                $data_riqi=date('Y-m-d',$data['riqi']);

                $spendtime=str_replace(array('小时','分钟'),'',$data['spendtime']);
                if($spendtime<10){
                    $min=$spendtime*60;
                }else{
                    $min=$spendtime;
                }
                $data_riqi2=date('H:i',strtotime($data_riqi.' '.$data['shijian'])+$min*60);

                //$textItem="{$riqi} {$value['uname']}取消了 {$data_riqi} {$data['shijian']}-{$data_riqi2}  {$data['name']}的{$data['buwei']}";
                $itemArr=array(
                    'riqi1'=>$riqi,
                    'uname'=>$value['uname'],
                    'riqi2'=>"{$data_riqi} {$data['shijian']}-{$data_riqi2}",
                    'name'=>$data['name'],
                    'buwei'=>$data['buwei'],
                );
                array_push($arrData,$itemArr);
            }
        }

        $this->assign("data",$arrData);
        return $this->fetch("Index/list_delete");
    }
}
